package com.sls.game.service.impl;

import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.socket.Head;
import com.sls.core.socket.ServerDisponseException;
import com.sls.core.socket.StartMain;
import com.sls.game.base.module.BaseDeal;
import com.sls.game.common.DeductionRefund;
import com.sls.game.component.SLSHttpInterfaceComponentImpl;
import com.sls.game.constant.ExceptionCodeDes;
import com.sls.game.pojo.DeductionRefundInfo;
import com.sls.game.pojo.GoodsOrderInfo;
import com.sls.game.pojo.GoodsSupplyManageInfo;
import com.sls.game.pojo.SLSHttpInterfaceInfo;
import com.sls.game.service.EKHAfterSupplyService;
import com.sls.game.service.EKHInterfaceService;
@Service("eKHInterfaceserviceImp")
public class EKHInterfaceserviceImp extends BaseServiceImp implements
		EKHInterfaceService, EKHAfterSupplyService {
	private static final long serialVersionUID = 812791341971731529L;

	private Gson gson = null;

	private static String SUPPLYDEAL = "supplybean";
	private static ResourceBundle supplybean = null;

	private static Logger log = Logger.getLogger(EKHInterfaceserviceImp.class);

	private SLSHttpInterfaceComponentImpl slsinterface = null;

	public EKHInterfaceserviceImp() {
		super();
		gson = CommonUtil.gson();

	}
	/**
	 * 未完成
	 * */
	@Deprecated
	@Override
	public String insertOfTrading(String body, Head head)
			throws ServerDisponseException {
		// TODO 交易总入口

		if (log.isInfoEnabled()) {
			log.info("请求ID：" + head.getRequestId()
					+ "，进入insertOfTrading方法，开始处理直充交易请求");
		}

		// 解析获取信息
		SLSHttpInterfaceInfo info = gson.fromJson(body,
				SLSHttpInterfaceInfo.class);
		// 交易前校验
		String beforeTrade = this.beforeTrade(info, head);

		if (beforeTrade != null) {
			return beforeTrade;
		}

		// GoodsSupplyManageInfo supplyManageInfo = this.selectSupplyInfo(info,
		// head, null);

		return null;
	}
	/**
	 * 未完成
	 * */
	@Override
	@Deprecated
	public String beforeTrade(SLSHttpInterfaceInfo info, Head head)
			throws ServerDisponseException {
		// TODO 交易前校验

		// 数据校验：该方法参数缺失直接报异常，所以，暂不对其返回结果进行校验
		slsinterface.checkDataOfInsertOfTrading(info, head.getRequestId());

		// 下游用户身份校验
		String result = null;
		try {
			result = slsinterface.checkIdentity(info.getUserNo(),
					info.getUserIP(), false);
		} catch (Exception e) {
			log.error("Service处理[" + head.getRequestId()
					+ "]的请求出现异常！获取下游身份校验异常：", e);
			throw new ServerDisponseException(
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getCode(),
					ExceptionCodeDes.ACCESS_DATABASE_ERROR.getDescription());
		}

		if ("104".equals(result)) { // 合作方用户不存在
			String resultBody = null;
			resultBody = slsinterface.returnUserNotExist();
			return resultBody;
		} else if ("105".equals(result)) {
			SLSHttpInterfaceInfo sLSHttpInterfaceInfo = new SLSHttpInterfaceInfo();
			sLSHttpInterfaceInfo.setResMsg("FAILED");
			sLSHttpInterfaceInfo.setFailedCode("105");
			sLSHttpInterfaceInfo.setFailedReason("绑定的IP地址不匹配");
			String resultBody = null;
			resultBody = gson.toJson(sLSHttpInterfaceInfo);
			return resultBody;
		}

		return null;
	}

	/**
	 * @description 获取商品供应信息：对商品供货信息进行筛选，对下游订单进行金额进行校验
	 * 
	 * @param head
	 *            消息头
	 * @param info
	 *            下游用户信息
	 * @param orderid
	 *            订单id号（主备切换用于） 对原订单内的供货商进行过滤
	 * @return 返回供应信息
	 * @throws ServerDisponseException
	 * */
	@Override
	@Deprecated
	public GoodsSupplyManageInfo selectSupplyInfo(SLSHttpInterfaceInfo info,
			Head head, String... orderid) throws ServerDisponseException {
		if (orderid != null) {

		}

		return null;
	}

	@Deprecated
	@Override
	public void checkAndInsertGoodsOrder(SLSHttpInterfaceInfo info,
			GoodsSupplyManageInfo goodsSupplyManageInfo, Head head,
			String orderId, String orderTime, String merchantIP)
			throws ServerDisponseException {
		// TODO Auto-generated method stub

	}
	
	@Deprecated
	@Override
	public DeductionRefundInfo trustPay(SLSHttpInterfaceInfo info, Head head,
			String orderId, String orderTime) throws ServerDisponseException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public SLSHttpInterfaceInfo insertTradeSupply(SLSHttpInterfaceInfo requestInfo,
			GoodsOrderInfo orderInfo, Head head, GoodsSupplyManageInfo goodsinfo)
			throws ServerDisponseException {
		String supplier = orderInfo.getSupplyId();

		String beanName = getDealName(supplier);

		BaseDeal basedeal = (BaseDeal) StartMain.APPLICATION_CONTEXT
				.getBean(beanName);

		GoodsOrderInfo returnOrder = null;
		try {
			// deal需要完成供货，并完成一次订单更新。
			returnOrder = basedeal.insertDealTrade(requestInfo, orderInfo, head,
					goodsinfo);
		} catch (Exception e) {
			e.printStackTrace();

		}

		if (returnOrder == null) {
			// 存疑
			GoodsOrderInfo orderInfo_e = new GoodsOrderInfo();
			orderInfo_e.setOrderId(orderInfo.getOrderId());
			orderInfo_e.setStatus("3");
			afterTraderException(orderInfo, head, requestInfo);
			returnOrder = orderInfo_e;
		}

		SLSHttpInterfaceInfo result_interfaceinfo = new SLSHttpInterfaceInfo();

		if ("1".equals(returnOrder.getStatus())) {
			// 成功
			result_interfaceinfo.setResMsg("SUCCESS");
			result_interfaceinfo.setPtOrderNo(requestInfo.getPtOrderNo());
			result_interfaceinfo.setStatus("ORDER_SUCCESS");
			result_interfaceinfo.setSupOrderNo(orderInfo.getOrderId());
			result_interfaceinfo.setSupOrderSuccessTime(returnOrder.getSupOrderSuccessTime());
		} else if ("0".equals(returnOrder.getStatus())) {
			// 失败
			result_interfaceinfo = afterTraderFault(returnOrder, head,
					requestInfo);
		} else if ("2".equals(returnOrder.getStatus())) {
			// 处理中
			result_interfaceinfo.setResMsg("SUCCESS");
			result_interfaceinfo.setFailedCode("209");
			result_interfaceinfo.setFailedReason("处理中");
			result_interfaceinfo.setPtOrderNo(requestInfo.getPtOrderNo());
			result_interfaceinfo.setStatus("ORDER_UNDERWAY");
			result_interfaceinfo.setSupOrderNo(orderInfo.getOrderId());
		} else {
			// 存疑
			result_interfaceinfo.setResMsg("SUCCESS");
			result_interfaceinfo.setFailedCode("210");
			result_interfaceinfo.setFailedReason("订单存疑");
			result_interfaceinfo.setPtOrderNo(requestInfo.getPtOrderNo());
			result_interfaceinfo.setStatus("ORDER_DUBIOUS");
			result_interfaceinfo.setSupOrderNo(orderInfo.getOrderId());
		}
		return result_interfaceinfo;
	}

	@Override
	@Deprecated
	public String traderChangeSupply(GoodsOrderInfo orderInfo, Head head,
			SLSHttpInterfaceInfo requestInfo) {
		// TODO主备切换
		return null;
	}

	@Override
	public SLSHttpInterfaceInfo traderFault(GoodsOrderInfo orderInfo,
			Head head, SLSHttpInterfaceInfo requestInfo) {
		// TODO确定失败最终处理，无其他后续操作。
		DeductionRefundInfo dedInfo = null;
		String paymentStatus = "";
		GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
		// 退款
		dedInfo = DeductionRefund.invokeDeductRefund(requestInfo,
				orderInfo.getOrderId(), "1", orderInfo.getPayTime(),
				orderInfo.getPaymentOrderNo(), head, getGoodsOrderDAO());

		if (dedInfo != null) {
			paymentStatus = dedInfo.getPaymentStatus();
		}
		if ("1".equals(paymentStatus)) { // 成功
			goodsOrderInfo.setIsPay("3"); // 退款成功
			// 退款成功，通知下游用户
			DeductionRefund.noticeUserRefundMsg(orderInfo.getOrderId(),
					dedInfo, getGoodsOrderDAO(), getDownstreamUserDAO(), null);

		} else if ("2".equals(paymentStatus)) {
			goodsOrderInfo.setIsPay("2"); // 退款失败
		}
		try {
			goodsOrderInfo.setOrderId(orderInfo.getOrderId());
			// 更新订单
			updateOrderInfo(goodsOrderInfo, head);
		} catch (Exception e) {
			log.error("请求ID：" + head.getRequestId() + "根据退款状态更新订单退款！",
					e);
		}

		return null;
	}

	@Override
	public String afterTraderSuccess(GoodsOrderInfo orderInfo, Head head,
			SLSHttpInterfaceInfo requestInfo) {
		// TODO 成功后订单更新
		updateOrderInfo(orderInfo, head);
		return null;
	}

	@Override
	public String afterTraderException(GoodsOrderInfo orderInfo, Head head,
			SLSHttpInterfaceInfo requestInfo) {
		updateOrderInfo(orderInfo, head);
		return null;
	}

	@Override
	public SLSHttpInterfaceInfo afterTraderFault(GoodsOrderInfo orderInfo,
			Head head, SLSHttpInterfaceInfo requestInfo) {
		// TODO 供货失败后操作
		// traderChangeSupply(orderInfo, head, requestInfo);
		traderFault(orderInfo, head, requestInfo);
		
		SLSHttpInterfaceInfo  sLSHttpInterfaceInfo  = new SLSHttpInterfaceInfo();
		
		sLSHttpInterfaceInfo.setResMsg("FAILED");
		sLSHttpInterfaceInfo.setFailedCode("208");
		sLSHttpInterfaceInfo.setFailedReason("充值失败");
		sLSHttpInterfaceInfo.setPtOrderNo(requestInfo.getPtOrderNo());
		sLSHttpInterfaceInfo.setStatus("ORDER_FAILED");
		sLSHttpInterfaceInfo.setSupOrderNo(orderInfo.getOrderId());
		
		return sLSHttpInterfaceInfo;
	}

	/** 从配置文件获取deal类名 */
	public static String getDealName(String key) {
		if (supplybean == null) {
			supplybean = ResourceBundle.getBundle(SUPPLYDEAL);
		}
		return supplybean.getString(key);
	}

	public SLSHttpInterfaceComponentImpl getSlsinterface() {
		return slsinterface;
	}

	public void setSlsinterface(SLSHttpInterfaceComponentImpl slsinterface) {
		this.slsinterface = slsinterface;
	}

}
